<script setup lang="ts">
import { h, reactive, ref, provide, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted } from 'vue';
import { useCounterStore } from './stores/counter';
import { storeToRefs } from 'pinia';
import { RouterView, useRouter } from 'vue-router'
import { NFlex, NButton, NIcon, NAvatar, NInput, NInputGroup, NDropdown, NText, NBadge, type DrawerPlacement, NSwitch, NCountdown, NPopover, NModal } from 'naive-ui';
import { NDivider, NNotificationProvider } from 'naive-ui';
import { NMessageProvider, NDialogProvider } from 'naive-ui';
import ComponentsMessage from './components/message.vue';
import ComponentsDialog from './components/dialog.vue';
import Notifier from './components/Notifier.vue';
import SvgIcon from './components/SvgIcon.vue';
import { encrypt, getJmg } from './service/jmg';

const componentsChat = defineAsyncComponent(() => import('./components/ComponentsChat.vue'))
/**
 * 状态管理
 */
const counterStore = useCounterStore()
const { isLogin, info, isInitialUser } = storeToRefs(counterStore)
const secret = ref('')
// const islogin = isLogin
// console.log('pinia的状态管理', counterStore.count)
// watch(() => counterStore.count, (newVal, oldVal) => {
//   console.log('pinia的状态管理', newVal, oldVal)
//   test.value = newVal
// })

const { dynamicApp } = storeToRefs(counterStore)
const activeApp = dynamicApp
console.log('pinia的动态路由', activeApp)

/**
 * end
 */

/**
 * 全局变量
 */
provide('wyy', 'wyytest')

/**
 * 固定应用项定义
 */
const router = useRouter();
const staticMenu = reactive([
  {
    名称: '我的应用',
    路由: 'application',
    图标: 'wodeyingyong',

  },
  {
    名称: '我的数据包',
    路由: 'dataset',
    图标: 'wodeshujuji',

  },
  {
    名称: '我的日程',
    路由: '日程',
    图标: 'wodericheng1',

  },
  {
    名称: 'Word文稿',
    路由: 'word',
    图标: 'Word-Color',

  },
  {
    名称: 'Excel表格',
    路由: 'excel',
    图标: 'Excel-Color',

  },
  {
    名称: '我的电话',
    路由: 'meeting',
    图标: 'shipinhuiyi',

  }
])

const routerMenu = (routepath: string, nameMenu: string) => {
  console.log('固定应用路由地址', routepath)
  router.push(routepath)
  handleMessage(nameMenu)
}

/**
 * end
 */

/**
* 动态应用项定义
*/

const routerActiveMenu = (name: string, nameMenu: string, icon: string, id: string) => {
  console.log('动态应用路由', name)
  router.push({
    name,
    params: {
      data: id
    }
  })
  handleMessage(nameMenu)
  counterStore.updateDynamicApp(id, false)
}


/**
 * end
 */

/**
 * 消息
 */
const message = ref<any>(null)
const dialog = ref<any>(null)
const handleMessage = (nameMenu: string) => {
  console.log('handleMessage')
  message.value.info(nameMenu + '应用打开！')

}
/**
 * end
 */

/**
 * 自定义平台顶部栏左侧头像的菜单功能
 */
//下拉菜单的头部信息
const renderCustomHeader = () => {
  return h(
    'div',
    {
      style: 'display: flex; align-items: center; padding: 8px 12px;'
    },
    [
      h(NAvatar, {
        round: true,
        style: 'margin-right: 12px;'
      }, () => h(SvgIcon, { iconClass: 'user__easyico', className: 'icon' })),
      h('div', { style: 'width: 150px;' }, [
        h('div', null, [h(NText, { depth: 2 }, { default: () => info.value.姓名 })]),
        h('div', { style: 'font-size: 12px;' }, [
          h(
            NText,
            { depth: 3 },
            { default: () => `${info.value.部门} ${info.value.职务}` }
          )
        ])
      ])
    ]
  )
}

// 下拉菜单的图标
let renderIcon = (icon: string) => {
  return h(NIcon, { size: 24 }, () => h(SvgIcon, { iconClass: icon }))
}
//下拉菜单项
const headerMenu = reactive([
  {
    key: 'header',
    type: 'render',
    render: renderCustomHeader
  },
  {
    key: 'header-divider',
    type: 'divider'
  },
  {
    label: '平台应用',
    key: '平台应用',
    icon: () => renderIcon('wodeyingyong2')
  },
  {
    label: '高级设置',
    key: '高级设置',
    icon: () => renderIcon('shezhi')
  },
  {
    label: 'AI帮助',
    key: '帮助',
    icon: () => renderIcon('ai')
  },
  {
    label: '互动交流',
    key: '互动交流',
    icon: () => renderIcon('dianhua1')
  },
  {
    label: '问题反馈',
    key: '问题反馈',
    icon: () => renderIcon('dianhua3')
  }
])
/**
 * end
 */

/**
* 自定义平台顶部栏右侧的退出下拉菜单功能
*/
const exitMenu = reactive([
  {
    key: 'header',
    type: 'render',
    render: renderCustomHeader
  },
  {
    key: 'header-divider',
    type: 'divider'
  },
  {
    label: '锁屏',
    key: 'lock',
    icon: () => renderIcon('suoping1')
  },
  {
    label: '退出',
    key: 'exit',
    icon: () => renderIcon('tuichu1')
  }
])
// 右侧下拉菜单项的点击事件
const handleSelect = (key: string) => {
  if (key === 'exit') {
    // 退出登录
    console.log('退出登录')
    window.location.href = '/login'
    // window.location.href = '/login'

  }
  if (key === 'lock') {
    // 锁屏
    console.log('锁屏')
    // router.push('/login')
    doLock()
  }
}
/**
 * end
 */
const showModal = ref(false)
const doLock = () => {
  showModal.value = true
}

/**
* 属性值
*/
const messageCount = ref<number>(8)
const messages = ref(Array.from({ length: messageCount.value }, (v,index) => ({
  title: '平台通知',
  content: `请点击查看更多`,
  description: '发达AI平台',
  meta: '2025-2-5 22:55.' + index,
})))

const offset = reactive<number | any>([-15, 37])

const drawerplacement = ref<DrawerPlacement>('right')

/**
 * end
 */



const openStaticContextMenu = (e: any) => {
  console.log('固定应用项响应这个右键事件', e)
}

const openAPPContextMenu = (e: any) => {
  console.log('动态应用项响应这个右键事件', e)
}
const openHeaderContextMenu = (e: any) => {
  console.log('顶部响应这个右键事件', e)
}
const openMainContextMenu = (e: any) => {
  console.log('主体响应这个右键事件', e)
}

/**
 * 定义右键菜单功能
 */

//定义右键菜单的变量值  show 值 x轴坐标 y轴坐标
const rightMenuShow = ref<boolean>(false)
const rightMenuX = ref<number>(0)
const rightMenuY = ref<number>(0)

// 动态菜单项的加载顺序
const dynamicMenuID = ref<number>(0)
//定义右键菜单的显示隐藏函数
const openContextMenu = (e: MouseEvent, index: number) => {
  // rightMenuShow.value = false
  e.preventDefault()
  dynamicMenuID.value = index
  console.log('响应这个右键事件', e.clientX, e.clientY)
  
  nextTick().then(() => {
    rightMenuShow.value = true
    rightMenuX.value = e.clientX
    rightMenuY.value = e.clientY
  })
  console.log('响应这个右键事件', rightMenuX.value, rightMenuY.value)
}
const handleClickOutside = (e: any) => {
  if (e.target) {
    rightMenuShow.value = false
    console.log('点击了内部区域')
  } else {
    console.log('点击了外部区域')
  }
}
/**
 * 动态应用的右键菜单操作
 */
const rightMenuOptions = reactive([
  {
    label: '关闭',
    key: 'close',

  },
  {
    label: '刷新',
    key: 'close-other',
  },
  {
    label: '固定',
    key: 'close-all',
  },
  {
    label: '打开',
    key: 'open',
  },

])
const drawerCloseApp = (key: string | number) => {
  if (key === 'close') {
    counterStore.removeDynamicApp(dynamicMenuID.value)
  }
  console.log('动态应用右键菜单选项',key)
  rightMenuShow.value = false
}
const rightmenuoutside = () => {
  rightMenuShow.value = false
}
/**
 * end
 */



/**
 * end
 */
const isHovered = ref()

const handleMouseOver = (index: number) => {
  isHovered.value = index
}

const handleMouseLeave = (index: number) => {
  isHovered.value = null
}
const isHoveredDy = ref()
const handleMouseOverDy = (index: number) => {
  isHoveredDy.value = index
}

const handleMouseLeaveDy = (index: number) => {
  isHoveredDy.value = null
}
/**
 * 定义聊天功能
 */
const isChatShow = ref<boolean>(false)


/**
 * 获取窗口宽度大小，以判定grid布局的显示的solt数量
 */
 const windowWidth = ref<number>(window.innerWidth)
const updateWindowWidth = () => {
  windowWidth.value = window.innerWidth
}
onMounted(() => {
  window.addEventListener('resize', () => {updateWindowWidth()})
  getJmg((reslut: any) => {
    if (!reslut.error) {
      secret.value = reslut.secret
    } else {
      message.value.error('加密狗加载失败')
    }
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', () => {updateWindowWidth()})
 })

 const password = ref('');
 const handleUnlock = async () => {
    let p = {
        username: info.value.工号,
        encryptedPassword: encrypt(password.value, secret.value),
        verify: true
    }
   const { LOG_UNLOCK } = await import('./service/apis/apis')
   LOG_UNLOCK({ params: JSON.stringify(p) }).then((res: any) => {
     console.log('登录返回结果', res);
     if (res.stacode == 200) {
       showModal.value = false
       message.value.success('已解锁')
     } else {
       message.value.error(res.message)
     }
   }).catch((err) => {
     message.value.error(err)
   });
}
</script>

<template>
  <n-modal v-model:show="showModal" preset="card" style="width: 600px" title="已锁定" :closable="false"
    :mask-closable="false">
    <n-input-group>
      <n-input v-model:value="password" type="password" placeholder="输入密码解锁" style="margin-bottom: 10px;"
        clearable @keydown.enter.native="handleUnlock" />
      <n-button type="primary" @click="handleUnlock" :disabled="password===''">
        <n-icon>
          <SvgIcon iconClass="unlock"></SvgIcon>
        </n-icon>
      </n-button>
    </n-input-group>
  </n-modal>
  <div class="app" v-if="!isLogin">
    <router-view></router-view>
  </div>
  <div v-else class="" @contextmenu.prevent="openAPPContextMenu" @click="handleClickOutside">
    <n-message-provider>
      <components-message ref="message" />
      <n-dialog-provider>
        <components-dialog ref="dialog" />
      </n-dialog-provider>
    </n-message-provider>
    <n-notification-provider>
      <!-- 顶部栏 -->
      <n-flex justify="space-between" :wrap="false" class="headerflex" @contextmenu.prevent="openHeaderContextMenu">
        <!-- 顶部栏左侧 -->
        <div class="header-flex">
          <n-flex justify="left" :wrap="false" class="flex-100">
            <n-dropdown trigger="hover" size="huge" :options="headerMenu" @select="handleSelect">
              <n-avatar size="large" :round="true">
                <n-icon>
                  <svg-icon iconClass="user__easyico" className="icon" />
                </n-icon>
              </n-avatar>
            </n-dropdown>
            <h1>山东发达AI数字化智慧平台</h1>
          </n-flex>
        </div>
        <!-- end -->
        <!-- 中间栏 -->
        <div class="header-flex">
          <n-flex justify="center" :wrap="false" class="flex-100">
            <n-countdown :duration="28800000"></n-countdown>
            <n-flex>当前窗口宽度大小：{{ windowWidth }}px</n-flex>
          </n-flex>


        </div>
        <!-- emd -->
        <!-- 右侧边 -->
        <div class="header-flex">
          <n-flex justify="right" :wrap="false" class="flex-100">

            <!-- 搜索 -->
            <n-input-group>
              <n-input :style="{ width: '35%',height: '28px' }" placeholder="输入文件名或关键词" />
              <n-button type="primary" size="small">
                搜索
              </n-button>
            </n-input-group>
            <!-- 搜索end -->
            <!-- 消息免打扰 -->
            <n-switch style="width: 100px;;">
              <template #unchecked>
                免扰
              </template>
              <template #checked>
                消息
              </template>
            </n-switch>
            <!-- 消息end -->
            <!-- 消息提醒事件 -->
            <n-badge :value="messageCount" :max="9">
              <Notifier v-model:messageCount="messageCount" v-model:messages="messages">
                <svg-icon iconClass="tongzhigonggao1" className="icon" />
              </Notifier>
            </n-badge>
            <!-- 消息end -->
            <!-- 关闭事件 -->
            <n-dropdown trigger="hover" :options="exitMenu" @select="handleSelect" :show-arrow="true">
              <n-button size="tiny" :bordered="false" type="success" circle>
                <template #icon>
                  <svg-icon iconClass="power" className="icon" />
                </template>
              </n-button>
            </n-dropdown>
            <!-- 关闭end -->
          </n-flex>
        </div>
        <!-- end -->
      </n-flex>
      <!-- 顶部栏 end -->
      <n-flex :size="0" vertical style="overflow-y: hidden; height: calc(100vh - 64px); border: 0px solid #dcdbdb;">
        <n-flex @contextmenu.prevent="openMainContextMenu"
          style="overflow-y: hidden; height: calc(100vh - 114px); border: 0px solid #d3b2b2;">
          <!-- 内容栏 -->
          <!-- 路由视图 -->
          <n-dialog-provider>
            <router-view />
          </n-dialog-provider>
        </n-flex>
        <component :is="componentsChat" v-model:isChatShow="isChatShow" />
        <!-- 底部导航栏 -->
        <n-flex v-if="!isInitialUser" justify="center" style="height: 50px; border: 0px solid #ca1616;" :size="0">
          <n-flex justify="center" :wrap="false" class="menu-item" :size="[0, 0]">
            <template v-for="(item, index) in staticMenu" :key="index">
              <n-popover trigger="hover">
                <template #trigger>
                  <n-button @click="routerMenu(item.路由, item.名称)" size="large" :bordered="false" ghost
                    class="fontcion32" @contextmenu.prevent="openStaticContextMenu">
                    <n-icon>
                      <n-badge dot type="success" :offset="offset">
                        <svg-icon :iconClass="item.图标" className="icon" :class="{ 'icon-hover': isHovered === index }"
                          @mouseover="handleMouseOver(index)" @mouseleave="handleMouseLeave(index)" />
                      </n-badge>
                    </n-icon>
                  </n-button>
                </template>
                <span>{{ item.名称 }}</span>
              </n-popover>
            </template>
            <n-button @click="isChatShow = !isChatShow" size="large" :bordered="false" ghost class="fontcion32">
              <n-icon>
                <svg-icon iconClass="weixin" className="icon" />
              </n-icon>
            </n-button>
          </n-flex>
          <n-divider vertical style="height: 100%;" v-if="activeApp.filter((item: any) => item.show).length" />
          <!-- 动态应用 -->
          <n-flex class="menu-item" :size="[0, 0]">
            <template v-for="(item, index) in activeApp.filter((item: any) => item.show)" :key="index">
              <n-popover trigger="hover">
                <template #trigger>
                  <n-button @click="routerActiveMenu(item.路由, item.名称, item.图标, item.缩写)" size="large" ghost
                    :bordered="false" class="fontcion32" @contextmenu.prevent="openContextMenu($event, index)">
                    <n-icon>
                      <n-badge dot type="success" :offset="offset">
                        <svg-icon :iconClass="item.图标" className="icon" :class="{ 'icon-hover': isHoveredDy === index }"
                          @mouseover="handleMouseOverDy(index)" @mouseleave="handleMouseLeaveDy(index)" />
                      </n-badge>
                    </n-icon>
                  </n-button>
                </template>
                <span>{{ item.名称 }}</span>
              </n-popover>
            </template>
          </n-flex>
          <n-flex>
            <n-dropdown style="width: 100px;" placement="bottom-start" trigger="manual" :show-arrow="true"
              :show="rightMenuShow" :options="rightMenuOptions" :y="rightMenuY" :x="rightMenuX"
              :on-clickoutside="rightmenuoutside" @select="drawerCloseApp">
            </n-dropdown>
          </n-flex>
          <!-- 动态应用end -->
        </n-flex>
      </n-flex>
      <!-- 底部导航栏 end -->
    </n-notification-provider>
  </div>
</template>

<style scoped>
.app {
  height: 100%;
  min-height: 700px;
  min-width: 430px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url('./assets/image/login.jpg') no-repeat;
  /* background-size: cover; */
  background-size: 100% 100%;
}

.headerflex {
  height: 64px;
  padding: 5px;
}

.n-layout-header {

  padding: 0px;

}

.n-layout-footer {
  height: 24px;
  padding: 1px;
}

.header-flex {
  display: grid;
  place-items: center;
  height: 54px;
  border: 0px solid #ca1616;
  width: calc(100% / 3);

}

.flex-100 {
  width: 100%;
}

.n-layout {
  overflow-y: hidden !important;
  /* height: calc(100vh - 124px) */
  background-color: #d3b2b2;
}

.n-layout::-webkit-scrollbar {
  display: none;
}

.n-layout-footer {
  background: none !important;
  opacity: 1;
}

.fontcion32 {
  font-size: 32px;
  
}

.menu-item {
  background-color: rgba(240, 240, 240, 0.6);
}

.icon-hover {
  transform: scale(1.5) translateY(-20%);
  box-shadow: 1px 4px 8px rgba(246, 246, 246, 0.9);
}
</style>
